#include <stddef.h>
#include <android/bitmap.h>
#include <android/log.h>
#include <string>
#include <sstream>

#define loge(str) __android_log_write(ANDROID_LOG_ERROR,"Log_From_JNI",str);

#define RGB565_R(p) ((((p) & 0xF800) >> 11) << 3)
#define RGB565_G(p) ((((p) & 0x7E0 ) >> 5)  << 2)
#define RGB565_B(p) ( ((p) & 0x1F  )        << 3)
#define MAKE_RGB565(r,g,b) ((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3))

#define RGBA_A(p) (((p) & 0xFF000000) >> 24)
#define RGBA_R(p) (((p) & 0x00FF0000) >> 16)
#define RGBA_G(p) (((p) & 0x0000FF00) >>  8)
#define RGBA_B(p)  ((p) & 0x000000FF)
#define MAKE_RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))


const char * int2str(int num){
    std::stringstream  ss;
    ss<<num;
    return ss.str().c_str();
}


extern "C"
JNIEXPORT void Java_libs_yzx_zaza_JNIActivity_bmp(JNIEnv *env,jclass jc,jobject jbmp){
    AndroidBitmapInfo info;
    AndroidBitmap_getInfo(env,jbmp,&info);

    //loge(int2str(info.width));     //bitmap宽度
    //loge(int2str(info.height));   //bitmap高度
    //loge(int2str(info.format));  //bitmap的Config (Argb8888....) , 在bitmap.h里边有枚举对应

    void * px = NULL;
    AndroidBitmap_lockPixels(env,jbmp,&px);

    for(int y=0;y<info.height;y++){
        for(int x=0;x<info.width;x++){
            /* 获取当前像素点位置 */
            int * nowPxPoint = (int *)px + y * info.width + x;
            /* 当前像素点位置的值 */
            int nowColorValue = *nowPxPoint;

            int r = RGBA_R(nowColorValue);
            int g = RGBA_G(nowColorValue);
            int b = RGBA_B(nowColorValue);
            int a = RGBA_A(nowColorValue);

            int gray = (r * 38 + g * 75 + b * 15) >> 7;
            *nowPxPoint = MAKE_RGBA(gray, gray, gray, a);
        }
    }

    AndroidBitmap_unlockPixels(env,jbmp);
}
